<?php

namespace App\Http\Middleware;

use App\Common\Tools;
use App\Services\Base\ApiLogService;
use Closure;
use Illuminate\Http\Request;

/**
 * api接口日志中间件
 *
 * @package App\Http\Middleware
 * @author WangBin
 * @date 2021-06/11
 */
class ApiLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $data['start_time'] = Tools::getMsec();
        // 调用接口
        $response = $next($request);

        $data['api_url'] = $request->getRequestUri();
        $data['remote_ip'] = $request->getClientIp();
        $data['params'] = $request->all();
        $data['response'] = $response->getContent() ? : '';
        $data['httpCode'] = 200;
        $data['end_time'] = Tools::getMsec();
        $data['run_time'] = $data['end_time'] - $data['start_time'];
        $data['status'] = $this->_getStatus($data['response']);
        // 保存日志
        ApiLogService::getInstance()->save($data);
        return $response;
    }

    /**
     * 判断接口是否返回成功
     *
     * @param $content
     * @return int
     */
    private function _getStatus($content)
    {
        $status = 0;
        try {
            $data = json_decode($content, true);
            if($data['errno'] == 0) {
                $status = 1;
            }
        }catch (\Exception $exception) {

        }
        return $status;
    }
}
